﻿namespace Anley.DomainDrivenDesign.Contract.Extension;

/// <summary>
/// 对象扩展类
/// </summary>
public static class ObjectExtensions
{
    /// <summary>
    /// 拷贝对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="source"></param>
    /// <param name="target"></param>
    public static void CopyTo<T>(this T source, T target)
    {
        var baseType = typeof(T);
        if (baseType == null)
            throw new ArgumentNullException(nameof(baseType));
        if (source == null)
            throw new ArgumentNullException(nameof(source));
        if (target == null)
            throw new ArgumentNullException(nameof(target));
        if (baseType.IsClass)
        {
            foreach (var prop in baseType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (prop.CanWrite)
                    prop.SetValue(target, prop.GetValue(source, null), null);
            }
        }
        else if (baseType.IsInterface)
        {
            var instType = baseType.GetInstanceType(true);
            foreach (var prop in instType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (prop.CanWrite)
                    prop.SetValue(target, prop.GetValue(source, null), null);
            }
        }
    }
}